package com.zonesion.robot.ai.ui;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zonesion.robot.ai.R;
import com.zonesion.robot.ai.TheApplication;
import com.zonesion.robot.ai.wifi.adapter.WifiapAdapter;
import com.zonesion.robot.ai.wifi.broadcast.WifiapBroadcast;
import com.zonesion.robot.ai.wifi.common.ConnWifiDialog;
import com.zonesion.robot.ai.wifi.consts.WifiApConst;
import com.zonesion.robot.ai.wifi.util.WifiUtils;

import java.util.ArrayList;
import java.util.List;

public class WIFIActivity extends AppCompatActivity implements WifiapBroadcast.NetWorkChangeListener,
    AbsListView.OnScrollListener, AdapterView.OnItemClickListener, View.OnClickListener {

  private ApHandler mHandler;
  private SearchWifiThread mSearchWifiThread;
  private ArrayList<ScanResult> mWifiList; //符合条件的热表列表
  private ConnWifiDialog mConnWifiDialog; // 连接热点窗口
  private WifiapAdapter mWifiApAdapter;
  private WifiapBroadcast mWifiapBroadcast;

  private TextView mTvStatusInfo;
  private ListView mLvWifiList;
  private Button mBtnBack;
  private Button mBtnNext;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wifi);
    initBroadcast(); // 注册广播
    initViews();
    initEvents();
    initAction();
  }

  //动态注册广播
  private void initBroadcast() {
    mWifiapBroadcast = new WifiapBroadcast(this);
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.setPriority(Integer.MAX_VALUE);
    registerReceiver(mWifiapBroadcast, filter);
  }

  //初始化视图 获取控件对象
  private void initViews() {
    mTvStatusInfo = findViewById(R.id.wifiap_tv_wifistatus);
    mLvWifiList = findViewById(R.id.wifiap_lv_wifi);
    mBtnBack = findViewById(R.id.wifiap_btn_back);
    mBtnNext = findViewById(R.id.wifiap_btn_next);
  }

  //初始化全局设置
  private void initEvents() {
    mWifiList = new ArrayList<ScanResult>();
    mWifiApAdapter = new WifiapAdapter(this, mWifiList);
    mLvWifiList.setAdapter(mWifiApAdapter);
    mHandler = new ApHandler();
    mConnWifiDialog = new ConnWifiDialog(this,mHandler);
    mSearchWifiThread = new SearchWifiThread(mHandler);
    mLvWifiList.setOnScrollListener(this);
    mLvWifiList.setOnItemClickListener(this);
    mBtnBack.setOnClickListener(view -> finish());
    mBtnNext.setOnClickListener(view -> finish());
  }

  /**
   * 初始化空间设置
   */
  @SuppressLint("SetTextI18n")
  protected void initAction(){

    if(!WifiUtils.isWifiConnect()) { //无连接wifi
      WifiUtils.OpenWifi();
    }
    if(WifiUtils.isWifiConnect()) {//wifi已连接
      mTvStatusInfo.setText("已连接到"+WifiUtils.getSSID());
      System.out.println("======================================"+WifiUtils.getWifiIP());

    }

    if(WifiUtils.isWifiEnabled() && !WifiUtils.isWifiConnect()) {//wifi已开启，未连接
      mTvStatusInfo.setText("WiFi已开启，未连接");
    }
    mSearchWifiThread.start();
  }

  private void getWifiList() {
    mWifiList.clear();
    WifiUtils.startScan();
    List<ScanResult> scanResults = WifiUtils.getScanResults();
    mWifiList.addAll(scanResults);
  }

  /**
   * 刷新热点列表UI
   *
   * @param list
   */
  public void refreshAdapter(List<ScanResult> list){
    mWifiApAdapter.setData(list);
    mWifiApAdapter.notifyDataSetChanged();
  }


  @Override
  public void onClick(View v) {
//        switch (v.getId()) {
//            //返回
//            case R.id.wifiap_btn_back:
//                finish();
//                break;
//            case R.id.wifiap_btn_next:
//                finish();
//                break;
//        }
  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
    switch (scrollState) {
      case  AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
        mHandler.setRespondFlag(true);
        break;
      case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
      case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
        mHandler.setRespondFlag(false);//滚动时不刷新列表
        break;
    }
  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

  }

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ScanResult ap = mWifiList.get(position);
    if(ap.SSID.startsWith(WifiApConst.WIFI_AP_HEADER)) {
      // 连接网络
      boolean connFlag = WifiUtils.connectWifi(ap.SSID, WifiApConst.WIFI_AP_PASSWORD,
          WifiUtils.WifiCipherType.WIFICIPHER_WPA);
      if(!connFlag) {
        mTvStatusInfo.setText("连接错误，请尝试重新连接。");
        mHandler.sendEmptyMessage(WifiApConst.WiFiConnectError);
      }
    }else if(!WifiUtils.isWifiConnect() || !ap.BSSID.equals(WifiUtils.getBSSID())) {
      mConnWifiDialog.setTitle(ap.SSID);
      mConnWifiDialog.setScanResult(ap);
      mConnWifiDialog.show();
    }
  }


  private class ApHandler extends Handler {
    private boolean isRespond = true;

    public ApHandler() {
    }

    public void setRespondFlag(boolean flag) {
      isRespond = flag;
    }
    @SuppressLint("SetTextI18n")
    @Override
    public void handleMessage(Message msg) {

      switch (msg.what) {
        case WifiApConst.ApScanResult://1 扫描wifi列表
          if(isRespond) {
            getWifiList();
            refreshAdapter(mWifiList);
          }
          break;
        case WifiApConst.WiFiConnectSuccess://2 连接成功
          String str = "已连接到"+ WifiUtils.getSSID();
          mTvStatusInfo.setText(str);
          Toast.makeText(TheApplication.getContext(),str,Toast.LENGTH_SHORT).show();
          break;
        case  WifiApConst.WiFiConnectError: //0  连接热点错误:
          Toast.makeText(TheApplication.getContext(),"连接错误，请检查密码后再尝试连接。",Toast.LENGTH_SHORT).show();
          break;
        case WifiApConst.NetworkChanged://3 wifi状态变化
          if(WifiUtils.isWifiEnabled()) {
            mTvStatusInfo.setText("WiFi已开启，未连接");
          }else {
            mTvStatusInfo.setText("WiFi未开启");
            Toast.makeText(TheApplication.getContext(),"WiFi连接已断开",Toast.LENGTH_SHORT).show();
          }
        default:
          break;
      }
    }
  }

  class SearchWifiThread implements Runnable {
    private boolean running = false;
    private Thread thread = null;
    private Handler handler = null;

    SearchWifiThread(Handler handler){
      this.handler = handler;
    }

    @Override
    public void run() {
      while (!WifiUtils.isWifiApEnabled()){
        if(!this.running)
          return;
        try {
          Thread.sleep(2000);//扫描间隔
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        handler.sendEmptyMessage(WifiApConst.ApScanResult);
      }
    }

    public void start() {
      try {
        this.thread = new Thread(this);
        this.running = true;
        this.thread.start();
      }
      finally {
      }
    }

    public void stop() {
      try {
        this.running = false;
        this.thread = null;
      }
      finally {
      }
    }
  }

  @Override
  public void WifiConnected() {
    mHandler.sendEmptyMessage(WifiApConst.WiFiConnectSuccess);
  }

  @Override
  public void wifiStatusChange() {
    mHandler.sendEmptyMessage(WifiApConst.NetworkChanged);
  }
}
